<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>添加销售退货订单</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        var saleOrderId = Ext.create('Ext.form.field.Hidden', {
          name: 'sale_order_id',
          value: '<%=params[:id]%>'
        });
        
        //备注
        var desc = Ext.create('Ext.form.field.Text', {
          fieldLabel: '备注',
          name: 'description',
          anchor: '97%'
        });
        
        //客户
        var customer = Ext.create('Ext.form.field.Text', {
          fieldLabel: '客户',
          allowBlank: false,
          readOnly: true,
          name: 'customer_name',
          anchor: '90%'
        });        

        //要求退货时间
        var returnDate = Ext.create('Ext.form.field.Date', {
          fieldLabel: '退货日期',
          allowBlank: false,
          name: 'return_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          blankText: "要求退货日期必须选择",
          emptyText: '退货日期...'
          //anchor: '50%'
        });
        
        //合同号
        var contractNumber = Ext.create('Ext.form.field.Text', {
          fieldLabel: '合同编号',
          allowBlank: true,
          readOnly: true,
          name: 'contract_number',
          anchor: '90%'
        });

        //联系人
        var linkman = Ext.create('Ext.form.field.Text', {
          fieldLabel: '联系人',
          name: 'linkman',
          allowBlank: false
        });
        
        //联系电话
        var phone = Ext.create('Ext.form.field.Text', {
          fieldLabel: '联系电话',
          name: 'phone',
          anchor: '95%',
          allowBlank: false
        });

        var receiveAddress = Ext.create('Ext.form.field.Text', {
          fieldLabel: '地址',
          allowBlank: false,
          name: 'delivery_address',
          anchor: '97%'
        });

        //总金额
        var sumAmount = Ext.create('Ext.form.field.Number', {
          fieldLabel: '总金额',
          name:"amount",
          readOnly:true,
          allowBlank: false,
          allowDecimals: true,
          minValue: 0,
          anchor: '90%'
        });

        var productCBB = Ext.create('Ext.form.ComboBox', {
          store: productAllInfoStore,
          emptyText: '请选择...',
          displayField: 'name',
          loadingText: '搜索中...',
          anchor: '100%',
          minChars: 0,
          listConfig: {
            loadingText: 'Searching...',
            getInnerTpl: function() {
              return '<div style="float:left; width:200px" data-qtip="{name}">{name:ellipsis(18)}</div><div style="float:left; width:110px">{number}</div>{is_suit}';
            }
          },
          pageSize: 10
        });

        //select( Ext.form.field.Picker field, Mixed value, Object options )
        productCBB.on('select', function(field, record, options) {
          //var saleOrderItemRecord = saleOrderDetailSM.getSelected();
          var sm = saleReturnedDetailGrid.getSelectionModel();
          var records = sm.getSelection();
          var saleOrderItemRecord = records[0];
          //alert(saleOrderItemRecord);
          if (!saleOrderItemRecord) {
            return false;
          }
          if (isDuplicateByProduct(saleReturnedDetailDS,record[0].get('id'),saleOrderItemRecord.id)){
            //删除当前记录
            saleReturnedDetailDS.remove(saleOrderItemRecord);
          }else{
            if (saleOrderItemRecord.get('product_id') != record[0].get('id')){
              saleOrderItemRecord.set('number',record[0].get('number'));
              saleOrderItemRecord.set('spec',record[0].get('spec'));
              saleOrderItemRecord.set('unit',record[0].get('unit'));
              saleOrderItemRecord.set('quantity',1);
              saleOrderItemRecord.set('discount',1);
              saleOrderItemRecord.set('product_id',record[0].get('id'));
              //判断套装
              saleOrderItemRecord.set('is_suit',record[0].get('is_suit'));
              //单价要特别拿出来处理,如果有销售类型的价格则使用，如果没有就使用销售类型的通用折扣。
            }
          }
          //从新计算得出总价。
          getSumAmount();
        });
        
        //--------------------------------------------------------------------------
        //新增销售订单信息Model
        Ext.define('SaleReturnedAddModel', {
          extend : 'Ext.data.Model',
          fields : [{
              name: 'id'
            }, {
              name: 'customer_name',
              mapping: 'customer.name'
            }, {
              name: 'amount'
            }, {
              name: 'description'
            }, {
              name: 'contract_number'
            }, {
              name: 'linkman'
            }, {
              name: 'phone'
            }, {
              name: 'tax_rate'
            }, {
              name: 'delivery_address'
            }
          ]
        });
        
        //新增销售退货订单详细信息Model
        Ext.define('SaleReturnedDetailAddModel', {
          extend : 'Ext.data.Model',
          fields : [{name: 'id'},
            { name: 'number'},
            { name: 'product_name'},
            { name: 'quantity',mapping:'balance_quantity', type: 'int'},
            { name: 'spec'},
            { name: 'unit'},
            { name: 'discount', type: 'float'},
            { name: 'description'},
            { name: 'unit_price', type: 'float'},
            { name: 'balance_quantity', type: 'int'},
            { name: 'product_id'},
            { name: 'amount', type: 'float'},
            {
              name: 'is_suit',
              mapping: 'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }
          ]
        });

        var saleReturnedDetailDS = Ext.create('Ext.data.Store', {
          autoDestroy : true,
          model : 'SaleReturnedDetailAddModel',
          proxy : {
            type : 'ajax',
            url: '/sale_returned/getSaleOrderDetailsByIdForReturned',
            extraParams:{sale_order_id:saleOrderId.getValue()},
            reader : {
              type : 'json',
              root : 'root',
              totalProperty : 'totalProperty'// 数据集记录总数
            }
          }
        });

        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
          clicksToEdit: 1
        });
        
        //生成要订单的产品的Grid
        var saleReturnedDetailGrid = Ext.create('Ext.grid.Panel', {
          store: saleReturnedDetailDS,
          plugins: [cellEditing],
          columns : [Ext.create('Ext.grid.RowNumberer'),{
              header: 'id',
              dataIndex: 'id',
              width: 45
            },{
              header: '产品名称',
              dataIndex: 'product_name',
              field: productCBB,
              width: 370
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: false
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 85
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 50
            },{
              header: '数量',
              align: 'right',
              dataIndex: 'quantity',
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: false,
                minValue: 1
              }),
              width: 50
            },{
              header: '折扣',
              dataIndex: 'discount',
              renderer: Ext.util.Format.numberRenderer('0,000.000'),
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: true,
                minValue: 0
              }),
              width: 45
            },{
              header: '单价',
              dataIndex: 'unit_price',
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: false,
                minValue: 0
              }),
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              align: 'right',
              width: 80
            },{
              header: '金额',
              dataIndex: 'amount',
              align: 'right',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              width: 80
            },{
              header: '套装或单品',
              dataIndex: 'is_suit',
              width: 70
            },{
              header: '备注',
              dataIndex: 'description',
              width: 110,
              field:Ext.create('Ext.form.field.Text', {
                name: 'description',
                anchor: '90%'
              })
            }],
          selModel :Ext.create('Ext.selection.CheckboxModel'),
          width: 1040,
          height: 290,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              handler : function(){
                var record = Ext.ModelManager.create({
                  product_name: '请选择产品'
                }, saleReturnedDetailGrid.getStore().model);
                saleReturnedDetailDS.insert(0, record);
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){                
                var sm = saleReturnedDetailGrid.getSelectionModel();
                var records = sm.getSelection();
                cellEditing.cancelEdit();
                saleReturnedDetailDS.remove(records);             
              }
            }]
        });

        //暂时保存按钮
        var submitButton = Ext.create('Ext.Button', {
          text: '提交',
          tooltip: '提交销售退货订单。',
          iconCls: 'icon-save',
          handler: function(){
            
            if (saleReturnedFormPanel.form.isValid()) {
              
              var productsJsonStr = gridStoreToJson(saleReturnedDetailDS,rejectKeyArray);
              if (saleReturnedDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              this.disable();
              var allJsonStr = saleReturnedFormPanel.getForm().getValues();
              allJsonStr = Ext.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/sale_returned/create',
                success : function (result, request) {
                  //Ext.MessageBox.alert("提示","提交成功");
                  newSaleReturnedWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  newSaleReturnedWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //暂时保存按钮
        var closeButton = Ext.create('Ext.Button', {
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            newSaleReturnedWin.destroy();
          }
        });
        
        //采购申请的FormPanel
        var saleReturnedFormPanel = Ext.create('Ext.form.Panel', {
          fieldDefaults: {
            labelWidth: 55,
            labelAlign: 'right'
          },
          width: '1055',
          frame : true,
          url: '/sale_returned/create',
          method: 'GET',
          reader: Ext.create('Ext.data.reader.Json',{
            model: 'SaleReturnedAddModel',
            root: 'root'
          }),
          //defaultType: 'textfield',
          items: [{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .4,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [customer]
                }, {
                  columnWidth: .3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [returnDate]
                }, {
                  columnWidth: .3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [contractNumber]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .4,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [linkman]
                }, {
                  columnWidth: .3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [phone]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [receiveAddress]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [desc]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [saleReturnedDetailGrid]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 0.3,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [sumAmount]
                }]
            },saleOrderId],
          buttons: [submitButton,closeButton]
        });

        saleReturnedFormPanel.form.load({
          url: '/sale_order/getSaleOrderById?id=' + <%=params[:id]%>,
          method : 'GET',
          waitMsg: '正在载入数据...',
          success: function(form, action){
            saleReturnedDetailDS.load({callback: function(record, options, success){
                getSumAmount();
              }
            });
          },
          failure: function(form, action){
            Ext.MessageBox.alert('提示信息', '信息加载失败');
          }
        });
        
        saleReturnedFormPanel.render('new_sale_returned');
        //
        saleReturnedDetailGrid.on('edit', afterEdit, this );

        function afterEdit(editor,obj,options) {
          //
          if(obj.field=="quantity"||obj.field=="unit_price"||obj.field=="discount"){
            if(obj.record.get('quantity')>0 && obj.record.get('unit_price') >0){
              obj.record.set('amount',obj.record.get('quantity')*100*obj.record.get('unit_price')*1000*obj.record.get('discount')/100000);
            }else{
              obj.record.set('amount',0);
            }
          }
          getSumAmount();
        }

        function getSumAmount(){
          sumAmount.setValue(0);
          var records = saleReturnedDetailDS.getRange(0,saleReturnedDetailDS.getCount());
          for(var i = 0; i< records.length ;i++){
            var record = records[i];
            var amount = record.get('amount');
            if (amount === undefined){
              amount = 0;
            }
            sumAmount.setValue(sumAmount.getValue()+Number(amount));
          }
        }
        
      })
    </script>
  </head>
  <body>
    <div id="new_sale_returned"></div>
  </body>
</html>